package com.pitaya.framework.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.pitaya.framework.common.Encrypt;
import com.pitaya.framework.common.Global;
import com.pitaya.framework.common.StringUtils;
import com.pitaya.winwine.domain.User;
import com.pitaya.winwine.service.UserService;

public class SecurityInterceptor implements HandlerInterceptor {
	@Autowired
	private UserService userService;

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception e) throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler, ModelAndView model) throws Exception {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		User user = new User();
		/*user.setId(1);
		request.getSession().setAttribute("user", user);*/
		if (request.getSession().getAttribute("user") == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (("winwineu".equals(cookie.getName())) && (cookie.getValue() != null)) {
						user.setUsername(Encrypt.decryptByDES(Global.key, cookie.getValue()));
					}
					if (("winwinep".equals(cookie.getName())) && (cookie.getValue() != null)) {
						user.setPassword(Encrypt.decryptByDES(Global.key, cookie.getValue()));
					}
				}
			}
			if ((user.getUsername() == null) || (user.getPassword() == null)
					|| (!this.userService.login(request, response, user).equals("success"))) {
				StringBuilder sb = new StringBuilder().append(Global.ctx).append("/login");
				String redirectUrl = request.getParameter("redirectUrl");
				if (StringUtils.isNotBlank(redirectUrl)) {
					sb.append("?redirectUrl=").append(redirectUrl);
				}
				String loginPage = sb.toString();
				Cookie cookie = new Cookie("winwineu", null);
				cookie.setMaxAge(0);
				response.addCookie(cookie);
				cookie = new Cookie("winwinep", null);
				cookie.setMaxAge(0);
				response.addCookie(cookie);
				response.sendRedirect(loginPage);
				return false;
			}
		}
		return true;
	}
}
